﻿using System;
using System.IO;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SpringStudio.Common
{
    public static class ExceptionHandler
    {
        public static void Handle(Exception exception)
        {
            try
            {
                string path = new AppSettingsReader().GetValue("ErrorLogPath", typeof(string)).ToString().Replace("/","\\");
                string str = string.Empty;
                str += "===================================================================" + "\r\n"
                    + "记录时间：" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n" + "错误消息：" + exception.Message + "\r\n" + "堆栈跟踪：" + "\r\n" + exception.StackTrace + "\r\n"
                    + "===================================================================" + "\r\n\r\n";

                // 先判断目录是否存在，如果不存在，则循环创建目录
                string dir = path.Substring(0,path.LastIndexOf("\\"));
                string[] dirSplit = dir.Split('\\');
                dir = dirSplit[0];
                for (int i = 1; i < dirSplit.Length; i++)
                {
                    dir += "\\" + dirSplit[i];
                    if (!Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }
                }

                StreamWriter sw = new StreamWriter(path, true);
                sw.Write(str);
                sw.Close();
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
            }
        }
    }
}
